import copy
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import AccessToken
from CloudGuardian.models import BindRelationship
from SecureHelperServer.settings import formatResponseData, JSON_TOKEN_KEY
from User.models import User, EmailVerificationRecord
from utils.conf import newID, newUserName, getUserByToken, newBindCode, Response
from utils.dateFun import getNowTimeStamp
from utils.loggingConfig import logger


class SelectUserLoginView(APIView):
    # 局部(本视图有效)身份认证
    authentication_classes = []
    # 局部(本视图有效)权限认证
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        选择用户登录
        """
        data = copy.deepcopy(formatResponseData)
        try:
            token = request.data.get("token")
            createNewWardUser = request.data.get("createNewWardUser")
            selectLoginType = request.data.get("selectLoginType")
            emailVerificationRecordId = request.data.get("emailVerificationRecordId")

            if not ((selectLoginType and emailVerificationRecordId) and (token or createNewWardUser)):
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            emailVerificationRecord = EmailVerificationRecord.objects.filter(id=emailVerificationRecordId).first()

            # 如果选择 注册新的监护对象
            if createNewWardUser:
                user = User(uid=newID(), username=newUserName(), bindCode=newBindCode())
                user.save()
                token = str(AccessToken.for_user(user))
                logger.info(f"选择用户登录：创建了新的被监护用户：user={user.uid}")

            else:
                user = getUserByToken(token)

            # 如果是通过监护人邮箱进行登录
            if selectLoginType == "loginByGuardianEmail":
                if createNewWardUser:
                    guardianUser = User.objects.filter(email=emailVerificationRecord.email).first()
                    BindRelationship(id=newID(), guardianUser=guardianUser, wardUser=user).save()
                    logger.info(f"选择用户登录：创建了新的绑定关系：guardianUser={guardianUser.uid}, wardUser={user.uid}")

            # 记录验证登录信息
            emailVerificationRecord.loginUser = user
            emailVerificationRecord.loginTimeStamp = getNowTimeStamp()
            emailVerificationRecord.isValid = False
            emailVerificationRecord.save()
            logger.info(f"选择用户登录：新的登录记录存档：user={user.uid}")

            data[JSON_TOKEN_KEY] = token
            return Response(data=data, responseMsg="登录成功", loggerMsg=f"选择用户登录：登录成功: uid={user.uid}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
